/**
 * Billing 模块 API
 * 账单计费相关接口
 */

import { request, type ApiResponse } from "../request";

// ============ 类型定义 ============

/**
 * 附加组件类型
 */
export type AddonType =
	| "custom_domain"
	| "compute_instance"
	| "pitr"
	| "ipv4"
	| "auth_mfa_phone"
	| "auth_mfa_web_authn"
	| "log_drain";

/**
 * 计算实例规格
 */
export type ComputeInstanceVariant =
	| "ci_micro"
	| "ci_small"
	| "ci_medium"
	| "ci_large"
	| "ci_xlarge"
	| "ci_2xlarge"
	| "ci_4xlarge"
	| "ci_8xlarge"
	| "ci_12xlarge"
	| "ci_16xlarge"
	| "ci_24xlarge"
	| "ci_24xlarge_optimized_cpu"
	| "ci_24xlarge_optimized_memory"
	| "ci_24xlarge_high_memory"
	| "ci_48xlarge"
	| "ci_48xlarge_optimized_cpu"
	| "ci_48xlarge_optimized_memory"
	| "ci_48xlarge_high_memory";

/**
 * 附加组件变体
 */
export type AddonVariant =
	| ComputeInstanceVariant
	| "cd_default"
	| "pitr_7"
	| "pitr_14"
	| "pitr_28"
	| "ipv4_default"
	| "auth_mfa_phone_default"
	| "auth_mfa_web_authn_default"
	| "log_drain_default";

/**
 * 价格类型
 */
export type PriceType = "fixed" | "usage";

/**
 * 价格间隔
 */
export type PriceInterval = "monthly" | "hourly";

/**
 * 价格信息
 */
export interface AddonPrice {
	description: string;
	type: PriceType;
	interval: PriceInterval;
	amount: number;
}

/**
 * 附加组件变体信息
 */
export interface AddonVariantInfo {
	id: AddonVariant;
	name: string;
	price: AddonPrice;
	meta?: Record<string, unknown>;
}

/**
 * 已选择的附加组件
 */
export interface SelectedAddon {
	type: AddonType;
	variant: AddonVariantInfo;
}

/**
 * 可用的附加组件
 */
export interface AvailableAddon {
	type: AddonType;
	name: string;
	variants: AddonVariantInfo[];
}

/**
 * 列出项目附加组件响应
 */
export interface ListProjectAddonsResponse {
	selected_addons: SelectedAddon[];
	available_addons: AvailableAddon[];
}

/**
 * 应用附加组件请求体
 */
export interface ApplyProjectAddonBody {
	addon_variant: AddonVariant;
	addon_type: AddonType;
}

// ============ API 方法 ============

/**
 * 列出项目账单附加组件和计算实例选择
 * 返回当前应用的账单附加组件，包括活动的计算实例大小，以及可配置的所有附加组件选项及定价元数据
 */
export function listProjectAddons(
	ref: string
): Promise<ApiResponse<ListProjectAddonsResponse>> {
	return request.get<ListProjectAddonsResponse>(
		`/v1/projects/${ref}/billing/addons`
	);
}

/**
 * 应用或更新账单附加组件，包括计算实例大小
 * 选择附加组件变体，例如扩展或缩小项目的计算实例
 */
export function applyProjectAddon(
	ref: string,
	data: ApplyProjectAddonBody
): Promise<ApiResponse<Record<string, unknown>>> {
	return request.patch<Record<string, unknown>>(
		`/v1/projects/${ref}/billing/addons`,
		data
	);
}

/**
 * 移除账单附加组件或恢复计算实例大小
 * 禁用所选的附加组件变体，包括将计算实例回滚到之前的大小
 */
export function removeProjectAddon(
	ref: string,
	addonVariant: AddonVariant
): Promise<ApiResponse<Record<string, unknown>>> {
	return request.delete<Record<string, unknown>>(
		`/v1/projects/${ref}/billing/addons/${addonVariant}`
	);
}

export default {
	listProjectAddons,
	applyProjectAddon,
	removeProjectAddon
};
